package modes

import (
	"fmt"
	"time"
)

/*
 * 描述: 题库名称介绍
 *
 *
 *****************************/

type TopicName struct {
	Id     int64  `json:"n_id"`                  //ID
	SId    int64  `json:"n_sid" xorm:"sid"`      //ID
	TypeId int    `json:"n_type" xorm:"type_id"` //类型ID (章节练习题，历年真题)
	Name   string `json:"n_name" xorm:"name"`    //题选项
	At     int64  `json:"n_at" xorm:"at"`        //时间
}

func (this *TopicName) TableName() string {
	return "toplibname"
}

func (this *TopicName) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *TopicName) Get() (bool, error) {
	return Db(0).Get(this)
}

func (this *TopicName) GetName() (bool, error) {
	w := fmt.Sprintf("type_id = %d and name = '%s'", this.TypeId, this.Name)
	return Db(0).Where(w).Get(this)
}

func (this *TopicName) IdDel() (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return Db(0).Where(where).Delete(this)
}

func (this *TopicName) WhereDel(tid int64) (int64, error) {
	where := fmt.Sprintf("tid = %d", tid)
	return Db(0).Where(where).Delete(this)
}

func (this *TopicName) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *TopicName) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *TopicName) PList(val *Pager) error {
	w := "start = 0"
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page, w, "")
	if err == nil {
		val.List = list
	}
	return err
}
func (this *TopicName) Count(where string) (int64, error) {
	var val TopicName
	return Db(0).Where(where).Count(&val)
}

func (this *TopicName) where(fage, count, page int, where, field string) ([]TopicName, error) {
	list := make([]TopicName, 0)
	var err error
	if field == "" {
		field = "id"
	}
	page--
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
